package com.spl.seriallibrary.mainserver;

import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.os.IBinder;
import android.util.Log;
import android.widget.Toast;

import com.spl.seriallibrary.locker.ILocker;
import com.spl.seriallibrary.locker.LockerFactory;
import com.spl.seriallibrary.util.Action;

import java.io.IOException;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.LinkedBlockingQueue;


public class MainServer extends Service {

    private Context mContext;
    private ILocker locker;
    private BlockingQueue<Intent> queue;
    ExecutorService service;

    @Override
    public void onCreate() {
        super.onCreate();
        mContext = this;
        try {
            locker = LockerFactory.getLocker(this);
        } catch (SecurityException e) {
            ShowMessage("打开串口失败:没有串口读/写权限！");
        } catch (IOException e) {
            ShowMessage("打开串口失败:设备不存在！");
        }
        queue = new LinkedBlockingQueue<>(100);
        service = Executors.newCachedThreadPool();
        service.execute(new Consumer(queue));
    }

    private void ShowMessage(String sMsg) {
        Toast.makeText(this, sMsg, Toast.LENGTH_SHORT).show();
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        queue.offer(intent);
        return super.onStartCommand(intent, flags, startId);
    }


    class Consumer implements Runnable {

        private BlockingQueue<Intent> queue;

        Consumer(BlockingQueue<Intent> queue) {
            this.queue = queue;
        }

        public void run() {
            while (true) {
                try {
                    Intent intent = queue.take();
                    if (intent != null) {
                        int action = intent.getExtras().getInt("action");
                        dispenseAction(action, intent);
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                    try {
                        Thread.sleep(1);
                    } catch (Exception ex) {
                        ex.printStackTrace();
                    }
                }
            }
        }
    }

    private void dispenseAction(int action, Intent intent) {
        switch (action) {
            case Action.IOCONTROLLER_OPEN_S:
                String olockNum = intent.getExtras().getString("boxid");
                locker.openLock(olockNum);
                break;
            case Action.IOCONTROLLER_QUERY_S:
                String qlockNum = intent.getExtras().getString("boxid");
                locker.queryLock(qlockNum);
                break;
            case Action.IOCONTROLLER_BATCH_OPEN_S:
                String[] obatchBoxId = intent.getExtras().getStringArray("batchboxid");
                locker.openLock(obatchBoxId);
                break;
            case Action.IOCONTROLLER_SIMPLEBATCHQUERY_S:
                String[] qbatchBoxId = intent.getExtras().getStringArray("batchboxid");
                locker.queryLock(qbatchBoxId);
                break;
            case Action.APP_REBOOT_S:
                long time = intent.getExtras().getLong("delayMs");
                reboot(time);
                break;
        }
    }

    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }


    private void reboot(long i) {
        final long delay = i;
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    Thread.sleep(delay);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                Intent intent = new Intent(Intent.ACTION_REBOOT);
                intent.putExtra("nowait", 1);
                intent.putExtra("interval", 1);
                intent.putExtra("window", 0);
                mContext.sendBroadcast(intent);
            }
        }).start();
    }
}
